package be.mapitall;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;



public class MapItAllActivity extends Activity {
  private static final int REQUEST_FILE_OPEN = 1;
  private static final String CAMERA_FILE_NAME = "MapItImage_";
  private static final String CAMERA_FILE_LOCATION = "/mnt/sdcard/map-it-all/";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addButtonListeners();
  }
  
  private void addButtonListeners(){
    //map from file
    Button createButton = (Button) findViewById(R.id.btnMapFromFile);
    createButton.setOnClickListener(new OnClickListener() {
      public void onClick(View view) {
        Intent myIntent = new Intent(view.getContext(), FileDialog.class);
        myIntent.putExtra(FileDialog.SELECTION_MODE, SelectionMode.MODE_OPEN);
        myIntent.putExtra(FileDialog.START_PATH, "/sdcard");
        startActivityForResult(myIntent, REQUEST_FILE_OPEN);
      }
    });
    
    //exit
    Button exitButton = (Button) findViewById(R.id.btnExit);
    exitButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        finish();
      }
    });
    
    //camera
    findViewById(R.id.btnMapFromCamera).setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        Camera theCamera = Camera.open();
        theCamera.takePicture( null, null, new PictureHandler() );
        theCamera.release();
      }
    });
    
  }

  public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
    if (resultCode == Activity.RESULT_OK) 
    {
      if (requestCode == REQUEST_FILE_OPEN) 
      {
        String mapfilepath = data.getStringExtra(FileDialog.RESULT_PATH);
        Intent myIntent = new Intent(this, MapViewActivity.class);
        myIntent.putExtra(MapViewActivity.MAP_FILE_PATH, mapfilepath);
        startActivityForResult(myIntent, 0);
      }
    }
    else if (resultCode == Activity.RESULT_CANCELED) 
    {
      System.out.println("File not selected");   
    }
  }
  
  private File findFirstUnusedFile(File aDirectory) throws IOException{
    if(!aDirectory.exists()) aDirectory.createNewFile();
    int theMaxIndex = 1;
    File[] theFiles = aDirectory.listFiles();
    for(File theFile : theFiles){
      if(theFile.getName().startsWith( CAMERA_FILE_NAME )){
        int theIndex = Integer.parseInt(theFile.getName().substring( CAMERA_FILE_NAME.length() ));
        if(theIndex > theMaxIndex){
          theIndex = theMaxIndex;
        }
      }
    }
    return new File(aDirectory, CAMERA_FILE_NAME + ++theMaxIndex);
  }
  
  private class PictureHandler implements PictureCallback {
    public void onPictureTaken( byte[] aBytes, Camera aCamera ) {
       FileOutputStream theOutputStream = null;
       try{
         theOutputStream = new FileOutputStream( findFirstUnusedFile( new File(CAMERA_FILE_LOCATION) ) );
         theOutputStream.write( aBytes );
         theOutputStream.flush();
       } catch(Exception e){
         //write some logging
       } finally {
         if(theOutputStream != null){
           try {
            theOutputStream.close();
          } catch ( IOException e ) {
            //write some logging
          }
         }
       }
    }
  }
}